package cn.edu.djtu.fw.action;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;

import cn.edu.djtu.fw.model.Goods;
import cn.edu.djtu.fw.model.Json;
import cn.edu.djtu.fw.model.Message;
import cn.edu.djtu.fw.model.Vgoods;
import cn.edu.djtu.fw.service.GoodsServiceI;
import cn.edu.djtu.fw.service.MessageServiceI;
import cn.edu.djtu.fw.service.SystemServiceI;
import cn.edu.djtu.fw.util.JsonUtil;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class GoodsAction extends ActionSupport implements ServletRequestAware {
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private GoodsServiceI goodsService;
	private MessageServiceI messageService;
	private SystemServiceI systemService;
	private Goods goods;
	private int gid;
	private int uid;
	private int page;
	private int rows;
	private String ids;
	private File image; // 上传的文件
	private String imageFileName; // 文件名称
	private String imageContentType; // 文件类型

	@Override
	public String execute() throws Exception {
		Map<String, Object> m = new HashMap<String, Object>();
		m = goodsService.getAllGoods(page, rows, goods);
		JsonUtil.writeJson(m);
		return null;
	}

	@SuppressWarnings("unchecked")
	public String show() throws Exception {
		HttpSession session = request.getSession();
		Vgoods vg = new Vgoods();
		vg = goodsService.getGoodsViewById(gid);
		if (vg != null) {
			Goods g = goodsService.getGoodsById(gid);
			g.setHitcount(vg.getHitcount() + 1);
			goodsService.update(g);
			Message msg = new Message();
			msg.setGid(gid);
			List<Message> messages = new ArrayList<Message>();
			messages = (List<Message>) messageService.getAllMessage(1, 10, msg).get("rows");
			if (messages.size() > 0) {
				session.setAttribute("msgdetail", messages);
			} else {
				session.setAttribute("msgdetail", "");
			}
			session.setAttribute("goodsdetail", vg);
			return "goodsShow";
		} else {
			session.setAttribute("error", "无此商品");
			return "goodsShow";
		}
	}

	@SuppressWarnings("unchecked")
	public String show2() throws Exception {
		HttpSession session = request.getSession();
		Vgoods vg = new Vgoods();
		vg = goodsService.getGoodsViewById(gid);
		if (vg != null) {
			Goods g = goodsService.getGoodsById(gid);
			g.setHitcount(vg.getHitcount() + 1);
			goodsService.update(g);
			Message msg = new Message();
			msg.setGid(gid);
			List<Message> messages = new ArrayList<Message>();
			messages = (List<Message>) messageService.getAllMessage(1, 10, msg).get("rows");
			if (messages.size() > 0) {
				session.setAttribute("msgdetail", messages);
			} else {
				session.setAttribute("msgdetail", "");
			}
			session.setAttribute("goodsdetail", vg);
			return "goodsShow2";
		} else {
			session.setAttribute("error", "无此商品");
			return "goodsShow2";
		}
	}

	public void add() throws Exception {
		Json j = new Json();
		try {
			goods.setCreatetime(new Date());
			fileUpload("images/goods", image);
			goods.setImgurl("images/goods/" + imageFileName);
			if (goodsService.insert(goods)) {
				j.setSuccess(true);
				j.setMsg("添加成功！");
			} else {
				j.setMsg("添加失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		JsonUtil.writeJson(j);
	}

	public String i_add() throws Exception {
		HttpSession session = request.getSession();
		try {
			goods.setCreatetime(new Date());
			if (image != null) {
				fileUpload("images/goods", image);
			} else {
				session.setAttribute("goods_add_msg", "*文件上传失败");
				return "goodsadd";
			}
			goods.setImgurl("images/goods/" + imageFileName);
			goods.setUid(uid);
			if (goodsService.insert(goods)) {
				systemService.refreshApplication(ActionContext.getContext().getApplication());
				session.setAttribute("goods_add_msg", "*发布成功");
				return "goodsadd";
			} else {
				session.setAttribute("goods_add_msg", "*发布失败");
				return "goodsadd";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "goodsadd";
	}

	public void update() throws Exception {
		Json j = new Json();
		if (imageFileName != null) {
			fileUpload("images/goods", image);
			goods.setImgurl("images/goods/" + imageFileName);
		} else {
			goods.setImgurl(goodsService.getGoodsById(gid).getImgurl());
		}
		if (goodsService.update(goods)) {
			j.setSuccess(true);
			j.setMsg("修改成功！");
		} else {
			j.setMsg("修改失败！");
		}
		JsonUtil.writeJson(j);
	}

	public String show_list() throws Exception {
		HttpSession session = request.getSession();
		Goods sgoods = null;
		if (session.getAttribute("sgoods") == null) {
			sgoods = new Goods();
		} else {
			sgoods = (Goods) session.getAttribute("sgoods");
		}
		if (type != null && type.length() > 0) {
			sgoods.setType(Integer.parseInt(type));
		}
		if (priceStart != null && priceStart.length() > 0) {
			sgoods.setPriceStart(new BigDecimal(priceStart));
		}
		if (priceEnd != null && priceEnd.length() > 0) {
			sgoods.setPriceEnd(new BigDecimal(priceEnd));
		}
		if (level != null && level.length() > 0) {
			sgoods.setLevel(Integer.parseInt(level));
		}
		if (location != null && location.length() > 0) {
			if ("null".equals(location)) {
				sgoods = new Goods();
				sgoods.setType(1);
			} else {
				sgoods.setLocation(Integer.parseInt(location));
			}
		}
		session.setAttribute("sgoods", sgoods);
		@SuppressWarnings("unchecked")
		List<Goods> s_g = (List<Goods>) goodsService.getAllGoods(1, 10, sgoods).get("rows");
		if (!s_g.isEmpty()) {
			session.setAttribute("s_g_list", s_g);
			//String pagination = PageUtil.createPaginationNoParam("../index/goods_show_list2.do", (long) goodsService.getAllGoods(page, 20, sgoods).get("total"), page, 8);
			//session.setAttribute("s_g_list_page", pagination);
			session.setAttribute("s_g_list_msg", null);
		} else {
			session.setAttribute("s_g_list", null);
			session.setAttribute("s_g_list_msg", "查无记录适当缩小条件 或者查看下边商品");
		}
		return "showGoodsList";
	}

	public String show_list2() throws Exception {
		HttpSession session = request.getSession();
		Goods sgoods = null;
		if (session.getAttribute("sgoods") == null) {
			sgoods = new Goods();
		} else {
			sgoods = (Goods) session.getAttribute("sgoods");
		}
		if (type != null && type.length() > 0) {
			sgoods.setType(Integer.parseInt(type));
		}
		if (priceStart != null && priceStart.length() > 0) {
			sgoods.setPriceStart(new BigDecimal(priceStart));
		}
		if (priceEnd != null && priceEnd.length() > 0) {
			sgoods.setPriceEnd(new BigDecimal(priceEnd));
		}
		if (level != null && level.length() > 0) {
			sgoods.setLevel(Integer.parseInt(level));
		}
		if (location != null && location.length() > 0) {
			if ("null".equals(location)) {
				sgoods = new Goods();
				sgoods.setType(1);
			} else {
				sgoods.setLocation(Integer.parseInt(location));
			}
		}

		session.setAttribute("sgoods", sgoods);
		@SuppressWarnings("unchecked")
		List<Goods> s_g = (List<Goods>) goodsService.getAllGoods(1, 20, sgoods).get("rows");
		if (!s_g.isEmpty()) {
			session.setAttribute("s_g_list", s_g);
			session.setAttribute("s_g_list_msg", null);
		} else {
			session.setAttribute("s_g_list", null);
			session.setAttribute("s_g_list_msg", "查无记录适当缩小条件 或者查看下边商品");
		}
		return "showGoodsList2";
	}

	@SuppressWarnings("unchecked")
	public String show_user_goods_list() throws Exception {
		HttpSession session = request.getSession();
		if (uid > 0) {
			Goods g = new Goods();
			g.setUid(uid);
			List<Goods> user_goods_list = (List<Goods>) goodsService.getAllGoods(1, 20, g).get("rows");
			if (user_goods_list != null) {
				session.setAttribute("user_goods_list", user_goods_list);
				return "showUserGoods";
			} else {
				session.setAttribute("user_goods_list", null);
				return "showUserGoods";
			}
		}
		return "showUserGoods";
	}

	public String i_update_show() throws Exception {
		HttpSession session = request.getSession();
		Goods g = goodsService.getGoodsById(gid);
		if (g != null) {
			session.setAttribute("update_goods", g);
		} else {
			session.setAttribute("update_goods", null);
		}
		return "er-update";
	}

	public String i_update() throws Exception {
		HttpSession session = request.getSession();
		if (imageFileName != null) {
			fileUpload("images/goods", image);
			goods.setImgurl("images/goods/" + imageFileName);
		} else {
			goods.setImgurl(goodsService.getGoodsById(gid).getImgurl());
		}
		goods.setCreatetime(goodsService.getGoodsById(gid).getCreatetime());
		goods.setUid(goodsService.getGoodsById(gid).getUid());
		goods.setHitcount(0);
		goods.setGid(gid);
		if (goodsService.update(goods)) {
			session.setAttribute("user_goods_update_msg", "* 修改成功");
		} else {
			session.setAttribute("user_goods_update_msg", "* 修改失败");
		}
		return "er-update";
	}

	public String i_delete() throws Exception {
		Goods c = goodsService.getGoodsById(gid);
		if (c != null) {
			goodsService.delete(c.getGid());
		}
		HttpSession session = request.getSession();
		if (uid > 0) {
			Goods g = new Goods();
			g.setUid(uid);
			@SuppressWarnings("unchecked")
			List<Goods> user_goods_list = (List<Goods>) goodsService.getAllGoods(1, 20, g).get("rows");
			if (user_goods_list != null) {
				session.setAttribute("user_goods_list", user_goods_list);
				return "showUserGoods";
			} else {
				session.setAttribute("user_goods_list", null);
				return "showUserGoods";
			}
		}
		return "showUserGoods";
	}

	public void delete() throws Exception {
		Json j = new Json();
		String[] idsStr = ids.split(",");
		for (int i = 0; i < idsStr.length; i++) {
			Goods c = goodsService.getGoodsById(Integer.parseInt(idsStr[i]));
			if (c != null) {
				goodsService.delete(c.getGid());
			}
		}
		j.setSuccess(true);
		j.setMsg("删除成功！");
		JsonUtil.writeJson(j);
	}

	public void fileUpload(String path, File inputFile) throws IOException {
		String realpath = ServletActionContext.getServletContext().getRealPath(path);
		System.out.println(realpath);
		if (inputFile != null) {
			File savefile = new File(new File(realpath), imageFileName);
			if (!savefile.getParentFile().exists())
				savefile.getParentFile().mkdirs();
			FileUtils.copyFile(inputFile, savefile);
		}
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public Goods getGoods() {
		return goods;
	}

	public void setGoods(Goods goods) {
		this.goods = goods;
	}

	public GoodsServiceI getGoodsService() {
		return goodsService;
	}

	@Autowired
	public void setGoodsService(GoodsServiceI goodsService) {
		this.goodsService = goodsService;
	}

	public MessageServiceI getMessageService() {
		return messageService;
	}

	@Autowired
	public void setMessageService(MessageServiceI messageService) {
		this.messageService = messageService;
	}

	@Override
	public void setServletRequest(HttpServletRequest req) {
		this.request = req;
	}

	public File getImage() {
		return image;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}

	public int getGid() {
		return gid;
	}

	public void setGid(int gid) {
		this.gid = gid;
	}

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public SystemServiceI getSystemService() {
		return systemService;
	}

	@Autowired
	public void setSystemService(SystemServiceI systemService) {
		this.systemService = systemService;
	}

	private String type;
	private String priceStart;
	private String priceEnd;
	private String level;
	private String location;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getLevel() {
		return level;
	}

	public void setLevel(String level) {
		this.level = level;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getPriceStart() {
		return priceStart;
	}

	public void setPriceStart(String priceStart) {
		this.priceStart = priceStart;
	}

	public String getPriceEnd() {
		return priceEnd;
	}

	public void setPriceEnd(String priceEnd) {
		this.priceEnd = priceEnd;
	}

}
